package cn.angis.system.service;

import cn.angis.db.service.BaseService;
import cn.angis.system.mapper.UserroleMapper;
import cn.angis.system.model.Userrole;
import org.apache.commons.collections4.CollectionUtils;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Transaction;

import java.util.ArrayList;
import java.util.List;

/**
* 用户角色关联表服务
* @author angis.cn
* @Date 2023-01-06
*/
@Component
public class UserroleService extends BaseService<UserroleMapper, Userrole> {
    @Inject
    private RoleresService roleresService;

    @Inject
    private AngisUserService angisUserService;

    @Transaction
    public int deleteByUserId(String userId) {
        return baseMapper.createLambdaQuery().andEq(Userrole::getUserId, userId).delete();
    }

    /**
     * 可在用户角色关联表
     * @param userId
 * @param roleIds
     * @return: void
     * @throws: 
     * @Date: 2023/1/8     
     */
    @Transaction
    public void saveUserRole(String userId, List<String> roleIds) {
        if (CollectionUtils.isNotEmpty(roleIds)) {
            this.deleteByUserId(userId);
            List<Userrole> userroleList = new ArrayList<>();
            roleIds.forEach(roleId -> userroleList.add(new Userrole(userId, roleId)));
            if (userroleList.size()>0) {
                this.saveBatch(userroleList);
                angisUserService.refreshUserByUserId(userId);
            }
        }
    }


}